package vn.gq.tym.comictemplate;
import org.json.JSONObject;
import vn.gq.tym.model.item.AdmobItem;
import vn.gq.tym.utils.Client;
import vn.gq.tym.utils.DataType;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.utils.NetworkOption;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;

public class StartupActivity extends Activity implements AdListener {

	private InterstitialAd intersitialAd;
	private CountDownTimer timer;
	private boolean pushedScreen = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_startup);
		
		timer = new CountDownTimer(5000, 1000) {
			
			@Override
			public void onTick(long millisUntilFinished) {
			}
			
			@Override
			public void onFinish() {
				pushScreen();
			}
		};
		timer.start();
		
		Client client = new Client(getApplicationContext());
		client.setCacheTime(3600000); // cache in 1 hour
		client.setNetworkOption(NetworkOption.OPTION_USE_CACHE);
		client.setOutputDataType(DataType.JSON);
		client.executeAndListener(String.format("http://apps.cucdinh.vn/ads/admob?id=%s&t=text", getPackageName()), new IClientListener() {
			
			@Override
			public void onDone(int code, Object result) {
				if (BuildConfig.DEBUG) {
					Log.e("longhoanggiang", String.valueOf(result));
				}
				AdmobItem admobItem = null;
				if (result != null) {
					try {
						admobItem = new AdmobItem((JSONObject) result);
						admobItem.setLoaded(true);
						admobItem.setPreference(getApplicationContext());
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		AdmobItem admobItem = AdmobItem.load(getApplicationContext());
		intersitialAd = new InterstitialAd(StartupActivity.this, admobItem.getAdsTypeFullScreen());
		intersitialAd.setAdListener(StartupActivity.this);
		AdRequest adRequest = new AdRequest();
		intersitialAd.loadAd(adRequest);
	}
	
	public void pushScreen() {
		if (!pushedScreen) {
			pushedScreen = true;
			Intent intent = new Intent(StartupActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		}
	}

	@Override
	public void onDismissScreen(Ad ad) {
	}

	@Override
	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
		Log.e(getClass().getSimpleName(), "---------------onFailedToReceiveAd");
		timer.cancel();
		pushScreen();
	}

	@Override
	public void onLeaveApplication(Ad arg0) {
	}

	@Override
	public void onPresentScreen(Ad arg0) {
	}

	@Override
	public void onReceiveAd(Ad ad) {
		timer.cancel();
		pushScreen();
		if (ad.isReady()) {
			((InterstitialAd) ad).show();
		}
	}

}
